package org.pausd.gunn.compsci;

import java.io.*;
import java.net.*;
/**
 * The main application, handles creating the classes, deciding if client/server
 * @author CodyS
 *
 */
class MultiCounter {
	public static void main(String[] args) throws IOException {
		String result = "";
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while (!result.equals("s") & !result.equals("c")) {
			System.out.println("Server or client? (s/c)");
			result = br.readLine();
		}
		if (result.equals("s")) {
			System.out.println("What port?");
			int port = Integer.valueOf(br.readLine());
			Game lg = new LocalGame();
			ConnectionListener cl = new ConnectionListener(lg,port);
			Thread t = new Thread(cl);
			t.start();
			Socket s = new Socket(cl.getAddress(),port);
			Game server = new NetworkGame(s);
			Player p = new LocalPlayer(server);
			server.addPlayer(p);
			
		} else {
			System.out.println("What location? (IP:Port)");
			String[] stuff = br.readLine().split(":");
			Socket s = new Socket(stuff[0], Integer.parseInt(stuff[1]));
			
			Game ng = new NetworkGame(s);
			Player lp = new LocalPlayer(ng);
			System.out.println("connected");
			ng.addPlayer(lp);
		}
	}
	/**
	 * Listens for new connections and adds them to the LocalGame (if this is the server)
	 * @author Data
	 *
	 */
	public static class ConnectionListener implements Runnable {
		private Game myGame;
		ServerSocket ss;
		public ConnectionListener(Game g,int port) {
			myGame = g;
			try {
				ss = new ServerSocket(port);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		public InetAddress getAddress() {
			return ss.getInetAddress();
		}
		/** 
		 * Listen for incoming connections and add them as Players to the game
		 */
		public void run() {
			while(true) {
				try {
					Socket s = ss.accept();
					myGame.addPlayer(new NetworkPlayer(myGame,s));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}